<template>
  <div class="view-wrapper">
    <div class="head">
      <el-form @submit.native.prevent :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入内容" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="listBox">
      <div style="margin-bottom: 14px" class="topBtn">
        <el-button type="primary" @click="handleAdd">新增规则</el-button>
      </div>
      <el-table v-loading="loading" :data="customerList" stripe border :span-method="arraySpanMethod">
        <el-table-column label="序号" type="index" width="55" align="center" fixed />
        <el-table-column label="规则名称" align="center" prop="incentiveRuleName" :show-overflow-tooltip="true" />
        <el-table-column label="贡献值" align="center" prop="contribution" :show-overflow-tooltip="true" />
        <el-table-column label="封顶激励值" align="center" prop="capping" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div>{{scope.row.capping}}%</div>
          </template>
        </el-table-column>
        <el-table-column prop="zaozuo" label="操作" align="center" width="120"  class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleEdit(scope.row)">
              编辑</el-button>
            <el-button size="mini" type="text" @click="handleDelete(scope.row)">
              删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        :pageSizes.sync="pageSizes" @pagination="getList" />

    </div>
    <add-activities
      ref="childRef"
      v-if="addActivities"
      :id="id"
      :pathType="pathType"
      :visible.sync="addActivities"
      @success="_handleSuccess" 
    />
  </div>

</template>

<script>
  import {
    ruleList,
    deleteRule
  } from "@/api/consumeMiningManagement/medalIncentive";
  import addActivities from './components/addActivities'
  export default {
    name: "",
    components: {
      addActivities
    },
    data() {
      return {
        // 遮罩层
        loading: false,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 会员列表表格数据
        customerList: [],
        // 页脚参数
        pageSizes: [10, 20, 30, 50, 1000],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: null,
        },
        date: [],
        levelTypeList: [],
        sourceList: [],
        addActivities: false,
        pathType: 'add',
        id: '',
       
        needMergeArr: ['incentiveRuleName', 'zaozuo'], // 有合并项的列
     	  rowMergeArrs: {}, // 包含需要一个或多个合并项信息的对象
      };
    },
    computed: {
      ExportParams() {
        const params = {
          ...this.queryParams,
        };
        return params;
      },
    },
    created() {
      this.getList();
    },
    mounted(){
    // 处理数据
      // this.rowMergeArrs = this.rowMergeHandle(this.needMergeArr, this.customerList); 
    },
    methods: {
      getlinkagelist() {
        //获取商户类型字典
        const params = {
          dictType: "customer_level_type",
        };
        adminDict(params).then((res) => {
          if (res.result.length != 0) {
            this.levelTypeList = res.result[0].dictList;
          }

        });
      },
      //获取渠道来源字典
      getSourcelist() {
        const params = {
          dictType: "bee_customer_source",
        };
        adminDict(params).then((res) => {
          this.sourceList = res.result[0].dictList;
        });
      },
      /** 查询会员列表列表 */
      getList() {
        this.loading = true;
        ruleList(this.queryParams).then(response => {
          console.log('response',response)
          this.total = response.result.total
          this.customerList = response.result.records
          this.rowMergeArrs = this.rowMergeHandle(this.needMergeArr, this.customerList); 
          // this.customerList = this.customerList.map(item => {
          //   // console.log('item',item)
          //   Object.keys(item).forEach(key => {
          //     if (item[key] === '') {
          //       item[key] = '-'
          //     }
          //   })
          //   return item
          // })
          // console.log('this.customerList', this.customerList)
          this.loading = false;
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        // this.resetForm();
        this.$refs["queryForm"].resetFields();
        this.date = []
        console.log('this.queryParams', this.queryParams)
        this.handleQuery();
      },
      /** 详情按钮操作 */
      handleView(row, type) {
        // this.$refs.dialog.open(row.id, true);
        this.$router.push({
          path: "/members/Prepaid-details",
          query: {
            id: row.id,
            type: type
          },
        })
      },
      
      //新增精选活动
      handleAdd(){
        this.addActivities = true
        this.pathType = 'add'
      },
      //编辑活动
      handleEdit(row){
        this.addActivities = true                                                                                                                                                                     
        this.pathType = 'edit'
        this.id =  row.incentiveRuleId
      },
			//查看
			handleLook(row){
        this.$router.push({
					path: '/blindBox/add-factoryConfig',
					query: {
						pathType: 'detail',
						id: row.id
					}
				})
			},
      //删除
			handleDelete(row){
        this.$confirm('是否删除', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            deleteRule(row.incentiveRuleId).then(res => {
              this.$message.success('操作成功')
              this.getList()
            })
          }).catch(() => {});
      },
      _handleSuccess(){
        this.getList()
      },
      /**
		     * @description 实现合并行或列
		     * @param row:Object 需要合并的列name 如:'name' 'id'
		     * @param column:Object 当前行的行数，由合并函数传入
		     * @param rowIndex:Number 当前列的数据，由合并函数传入
		     * @param columnIndex:Number 当前列的数据，由合并函数传入
		     *
		     * @return 函数可以返回一个包含两个元素的数组，第一个元素代表rowspan，
		     * 第二个元素代表colspan。 也可以返回一个键名为rowspan和colspan的对象
		    */
		    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
          console.log('column',column)
		        // 没办法循环判断具体是那一列 所以就只好写了多个if
		        if (column.property === 'incentiveRuleName') 
		        return this.mergeAction('incentiveRuleName', rowIndex, column);
            if (column.property === 'zaozuo') 
            return this.mergeAction('zaozuo', rowIndex, column);

            
		    },
		    /**
		     * @description 根据数组来确定单元格是否需要合并
		     * @param val:String 需要合并的列name 如:'name' 'id'
		     * @param rowIndex:Number 当前行的行数，由合并函数传入
		     * @param colData:Object 当前列的数据，由合并函数传入
		     *
		     * @return 返回值为一个数组表示该单元格是否需要合并;
		     *  说明: [0,0]表示改行被合并了 [n+,1]n为1时表示该单元格不动,
		     * n大于1时表示合并了N-1个单元格
		    */
		    mergeAction(val, rowIndex, colData) {
          // console.log('this.rowMergeArrs', this.rowMergeArrs)
		        let _row = this.rowMergeArrs[val].rowArr[rowIndex];
		        let _col = _row > 0 ? 1 : 0;
		        return [_row, _col];
		    },
		    /**
		     * @description 根据数组将指定对象转化为相应的数组
		     * @param arr:Array[String] 必填 必须是字符串形式的数组
		     * @param data:Array 必填 需要转化的对象
		     *
		     * @return 返回一个对象
		     * 例：rowMerge(['name','value'],
		     *  [{value:'1', name:'小明'},
		     *  {value:'2', name:'小明'}, 
		     * {value:'3', name:'小明'}, 
		     * {value:'1', name:'小明'}, 
		     * {value:'1', name:'小明'}])
		     * 返回值: {
		     *          name:{
		     *            rowArr: [5, 0, 0, 0, 0]
		     *            rowMergeNum: 0,
		     *          },
		     *          value: {
		     *            rowArr: [1, 1, 1, 2, 0],
		     *            rowMergeNum: 3
		     *          }
		     *        }
		    */
		    rowMergeHandle(arr, data) {
		      if (!Array.isArray(arr) && !arr.length) return false;
		      if (!Array.isArray(data) && !data.length) return false;
		      let needMerge = {};
		      arr.forEach(i => {
		        needMerge[i] = {
		          rowArr: [],
		          rowMergeNum: 0
		        };
		        data.forEach((item, index) => {
		          if (index === 0) {
		            needMerge[i].rowArr.push(1);
		            needMerge[i].rowMergeNum = 0;
		          } else {
		            if (item['incentiveRuleName'] === data[index - 1]['incentiveRuleName']) {
                  console.log('item[i]',item[i])
                  console.log('data[index - 1][i]',data[index - 1][i])
		              needMerge[i].rowArr[needMerge[i].rowMergeNum] += 1;
		              needMerge[i].rowArr.push(0);
		            } else {
		              needMerge[i].rowArr.push(1);
		              needMerge[i].rowMergeNum = index;
		            }
		          }
		        });
		      });
		      return needMerge;
		    }
    }
  };

</script>
<style lang="scss" scoped>
  .head {
    box-shadow: 0px 4px 12px 0px rgb(1 41 99 / 6%);
    background-color: #fff;
    border-radius: 8px;
    padding: 20px 20px 0;
  }

  .listBox {
    box-shadow: 0px 4px 12px 0px rgb(1 41 99 / 6%);
    background-color: #fff;
    border-radius: 8px;
    //   height: 120px;
    padding: 20px 20px;
    margin-top: 10px;
  }
  .imgBox{
    display: flex;
    justify-content: center;
    width: 100%;
    img{
      width: 150px;
      height: 100px;
    }
  }
</style>
